package cn.edu.guet.tts.controller;

import cn.edu.guet.tts.common.Result;
import cn.edu.guet.tts.entity.TbTicket;
import cn.edu.guet.tts.service.ITbTicketService;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.net.URLEncoder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.guet.tts.service.ITbOrderService;
import cn.edu.guet.tts.entity.TbOrder;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 订单管理表 前端控制器
 * </p>
 *
 * @author test
 * @since 
 */
@RestController
@RequestMapping("/tbOrder")
public class TbOrderController {

    private static final Logger log = LoggerFactory.getLogger(TbOrderController.class);
    @Resource
    private ITbOrderService tbOrderService;
    @Resource
    private ITbTicketService tbTicketService;

    /**
     * 新增或保存
     * @param tbOrder
     * @return
     */
    @Transactional
    @PostMapping
    public Result save(@RequestBody TbOrder tbOrder) {
        log.info("新增或更新订单：{}", tbOrder);
        tbOrderService.saveOrUpdate(tbOrder);
        TbTicket tbTicket = tbTicketService.getById(tbOrder.getTicketId());
        String status = tbOrder.getOrderStatus();
        if(status.equals("已支付")){
            tbTicket.setTicketStatus("售票");
        }else if(status.equals("退票受理中")){
            tbTicket.setTicketStatus("退票");
        }else if(status.equals("已退票")){
            tbTicket.setTicketStatus("未售出");
        }else{
            return Result.error("400","订单状态错误");
        }
        log.info("更新订单车票状态：{}", tbTicket);
        tbTicketService.updateById(tbTicket);
        return Result.success();
    }

    /**
     * 根据订单id删除
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        TbOrder order = tbOrderService.getById(id);
        // 级联修改订单车票的状态为 未售出
        TbTicket ticket = tbTicketService.getById(order.getTicketId());
        ticket.setTicketStatus("未售出");
        tbTicketService.updateById(ticket);
        return Result.success(tbOrderService.removeById(id));
    }

    /**
     * 根据订单id批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(tbOrderService.removeByIds(ids));
    }

    /**
     * 查询所有订单
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(tbOrderService.list());
    }

    /**
     * 根据订单id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(tbOrderService.getById(id));
    }

    /**
     * 根据车票id查询订单
     * @param id
     * @return
     */
    @GetMapping("/getOrderByTicketId/{id}")
    public Result getOrderByTicketId(@PathVariable Integer id) {
        return Result.success(tbOrderService.getOrderByTicketId(id));
    }


    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String userId,
                           @RequestParam(defaultValue = "") String userName,
                           @RequestParam(defaultValue = "") String status,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<TbOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(userId)) {
            queryWrapper.like("user_id", userId);
        }
        if (!"".equals(userName)) {
            queryWrapper.like("fullname", userName);
        }
        if (!"".equals(status)) {
            queryWrapper.like("order_status", status);
        }
        return Result.success(tbOrderService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
    
    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        try {
            log.info("开始导出订单数据");
            // 从数据库查询出所有的数据
            List<TbOrder> list = tbOrderService.list();
            if (list == null || list.isEmpty()) {
                log.warn("没有找到订单数据");
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            
            // 在内存操作，写出到浏览器
            ExcelWriter writer = ExcelUtil.getWriter(true);
            // 一次性写出 list 内的对象到excel，使用默认样式，强制输出标题
            writer.write(list, true);
            
            // 设置浏览器响应的格式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("订单信息", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
            log.info("订单数据导出成功");
        } catch (Exception e) {
            log.error("导出订单数据时发生错误", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }
}

